import { createLogger, format, Logform, transports } from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';

const isDev = process.env.NODE_ENV !== 'production';

const setupLogger = () => {
  const logger = createLogger({
    level: isDev ? 'debug' : 'info', // MUST be LowerCase
    format: format.combine(
      format.label({ label: 'WebFront' }),
      format.splat(),
      format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss',
      }),
      format.colorize(),
      format.printf(
        (info: Logform.TransformableInfo) =>
          `[${info.timestamp}][${info.level}][${process.pid}][${info.label}] ${info.message}`,
      ),
    ),
    exitOnError: false,
    transports: [
      new transports.Console(), // default transport
    ],
  });

  if (!isDev) {
    logger.add(
      new DailyRotateFile({
        format: format.combine(format.uncolorize()),
        filename: 'webfront-%DATE%.log',
        datePattern: 'YYYY-MM-DD', // rotate daily without size limitation
        dirname: `./server/log`,
        zippedArchive: true,
        maxFiles: '30d',
      }),
    );
  }

  // Override the base console log with winston
  //console.log = (args: any[]) => logger.info.apply(logger, [args]);
  console.debug = (args: any[]) => logger.debug.apply(logger, [args]);
  console.info = (args: any[]) => logger.info.apply(logger, [args]);
  console.warn = (args: any[]) => logger.warn.apply(logger, [args]);
  console.error = (args: any[]) => logger.error.apply(logger, [args]);
};

export default setupLogger;
